/*global window: false, soundManager: false*/
/*
 * #depends playlist-controller.js
 */
Ext.ns('Ext.ux.mattgoldspink.subsonic.controllers');

Ext.ux.mattgoldspink.subsonic.controllers.Playlist = function(){
    // setup msg bus
    this.msgbus = new Ext.ux.MsgBus();
    this.msgbus.init(this);
    this.subscribe('subsonic.playlist.created', {
        scope: this,
        fn: this.createPlaylist
    });
	this.subscribe('subsonic.playlist.track.added', {
        scope: this,
        fn: this.trackAdded
    });
	this.subscribe('subsonic.playlist.track.removed', {
        scope: this,
        fn: this.trackRemoved
    });
	this.subscribe('subsonic.playlist.renamed', {
        scope: this,
        fn: this.playlistRenamed
    });
};

Ext.apply(Ext.ux.mattgoldspink.subsonic.controllers.Playlist.prototype, {
    createPlaylist: function(subject, playlist) {
		// it has to have one track before it can be added to the server so we cache it locally first
		var newPlaylists = Ext.ux.mattgoldspink.subsonic.UserPrefsStore.get('unsaved-playlists', []);
		newPlaylists.push(playlist.name);
		Ext.ux.mattgoldspink.subsonic.UserPrefsStore.get('unsaved-playlists', newPlaylists);
	},
	trackAdded: function(subject, data) {
		var playlistName = data.name, playlistId = data.playlistId, songId = [];
		Ext.each(data.songs, function(song) {
			songId.push(song.id);
		});
		var baseParams = Ext.apply({
			songId: songId
		}, Ext.ux.mattgoldspink.subsonic.LoginDetails);
		if (playlistId && Ext.ux.mattgoldspink.subsonic.isVersionGreaterThan(window.subtunes.serverVersion, "1.4.0")) {
			baseParams.playlistId = playlistId;
		} else {
			baseParams.name = playlistName;
		}
		if (playlistId) {
            this.getExistingTracksForPlaylist(playlistId, function(response, options){
                var json = response.responseData;
                if (!Ext.isArray(json.playlist.entry)) {
                    json.playlist.entry = [json.playlist.entry];
                }
                var cacheExistingIds = baseParams.songId;
                baseParams.songId = [];
                Ext.each(json.playlist.entry, function(item){
                    baseParams.songId.push(item.id);
                });
                Ext.each(cacheExistingIds, function(item){
                    baseParams.songId.push(item);
                });
                this.doCreatePlaylistCall(baseParams, this.handleTrackAddSuccess);
            });
        }else {
	        this.doCreatePlaylistCall(baseParams, this.handlePlaylistCreatedSuccess);
	    }
	},
	doCreatePlaylistCall: function(baseParams, success) {
	    Ext.Ajax.request({
		    url: Ext.ux.mattgoldspink.subsonic.apiUrl + '/rest/createPlaylist.view',
		    params: baseParams,
            method: 'GET',
		    success: Ext.isEmpty(success)? this.handleTrackAddSuccess : success,
		    scope: this,
		    failure: this.handleTrackAddFailure
	    });
	},
	getExistingTracksForPlaylist: function(playlistId, executeOnResponse) {
		Ext.Ajax.request({
			url: Ext.ux.mattgoldspink.subsonic.apiUrl + '/rest/getPlaylist.view',
			params: Ext.apply({
			        id: playlistId
		        }, Ext.ux.mattgoldspink.subsonic.LoginDetails),
            method: 'GET',
			success: executeOnResponse,
			scope: this,
			failure: this.handleTrackAddFailure
		});
	},
	handlePlaylistCreatedSuccess: function(response, options) {
	    this.publish('subsonic.playlist.created.success', options.params.name);
	},
	handleTrackAddSuccess: function(response, options) {
		this.publish('subsonic.playlist.updated.success', options.params.playlistId);
	},
	handleTrackAddFailure: function(response, options) {
		//alert('epic fail');
	},	
	trackRemoved: function(subject, data) {
	
	},
	makeDoDeletePlaylistCall: function(playlistId) {
	    return function(response, options){
           if (response.responseData.status === 'ok') {
	            Ext.Ajax.request({
			        url: Ext.ux.mattgoldspink.subsonic.apiUrl + '/rest/deletePlaylist.view',
			        params: Ext.apply({
			                id: playlistId
		                }, Ext.ux.mattgoldspink.subsonic.LoginDetails),
                    method: 'GET',
			        success: this.handleDeleteSuccess,
			        scope: this,
			        failure: this.handleDeleteFailure
		        });
	        }
	    };
	},
	handleDeleteFailure: function(response, options) {
	
	},
	handleDeleteSuccess: function(response, options) {
	    this.publish('subsonic.playlist.renamed.success', options.params);
	},
	playlistRenamed: function(subject, data) {
        this.getExistingTracksForPlaylist(data.id, function(response, options){
	        var json = response.responseData, baseParams = Ext.apply({
                name: data.text,
                songId: []
            }, Ext.ux.mattgoldspink.subsonic.LoginDetails);
            if (!Ext.isArray(json.playlist.entry)) {
                json.playlist.entry = [json.playlist.entry];
            }
            Ext.each(json.playlist.entry, function(item) {
                baseParams.songId.push(item.id);
            });
	        this.doCreatePlaylistCall(baseParams, this.makeDoDeletePlaylistCall(data.id));
	    });
	}
});
Ext.ux.mattgoldspink.subsonic.controllers.Playlist.singleton = new Ext.ux.mattgoldspink.subsonic.controllers.Playlist();
